package org.kl.bf.web.basic;

import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.kl.bf.entity.basic.Calendar;
import org.kl.bf.entity.basic.CalendarType;
import org.kl.bf.entity.basic.User;
import org.kl.bf.service.basic.CalendarService;
import org.kl.bf.service.basic.CalendarTypeService;
import org.kl.bf.utils.BasicConstants;
import org.kl.bf.utils.ExcelWriter;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

/**
 * 日程管理
 * 
 * @Author hqm
 * @CreateTime 2014-3-13 下午9:34:36
 */
@Controller
@RequestMapping(value = "/basic/calendar")
public class CalendarController extends BasicController {
	@Autowired
	private CalendarService calendarService;
	@Autowired
	private CalendarTypeService calendarTypeService;

	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "basic/calendarList";
	}

	// @RequiresPermissions("calendar:list")
	@RequestMapping(value = "json", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String json(@RequestParam(value = "start", defaultValue = "") String start,
			@RequestParam(value = "end", defaultValue = "") String end, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		searchParams.put("EQ_user.id", BasicController.getCurrentUserId());
		DateTime st = null, et = null;
		if (StringUtils.isBlank(start)) {
			st = new DateTime("yyyy-MM-dd HH:mm:ss").minusMonths(1).dayOfMonth().withMinimumValue().withTimeAtStartOfDay();// 上个月月初
			searchParams.put("GTE-T_start", st.toString("yyyy-MM-dd HH:mm:ss"));
		} else {
			searchParams.put("GTE-T_start", start + " 00:00:00");
		}
		if (StringUtils.isBlank(end)) {
			et = new DateTime("yyyy-MM-dd HH:mm:ss").plus(1).dayOfMonth().withMaximumValue().millisOfDay().withMaximumValue();// 下个月月末
			searchParams.put("LTE-T_end", et.toString("yyyy-MM-dd HH:mm:ss"));
		} else {
			searchParams.put("LTE-T_end", end + " 00:00:00");
		}
		int pageSize = 100;//月事件数设置为100
		Page<Calendar> calendars = calendarService.getUserCalendar(searchParams, 1, pageSize, "start", "asc");
		String result = jsonMapper.toJson(calendars.getContent());
		return result;
	}

	/**
	 * 我的日程条数
	 * 
	 * @return
	 */
	@RequestMapping(value = "calendar-count", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String calendarCount() {
		long count = calendarService.getCalendarListBystartGreaterThan(new Timestamp(new DateTime().getMillis()), BasicController.getCurrentUserId()).size();
		return ajaxMsg("我的日程条数获取成功", true, count);
	}

	@RequestMapping(value = "excelExport", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String excelExport(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		Page<Calendar> calendars = calendarService.getUserCalendar(searchParams, pageNumber, 0, sortType, orderType);
		try {
			// 输出Excel文件.
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition",
					"attachment;filename=\""
							+ new String(("日程管理" + new DateTime().toString("yyyyMMddHHmmss") + ".xls").getBytes("gb2312"), "ISO8859-1")
							+ "\"");
			ExcelWriter.exportExcel("日程管理", Calendar.class, calendars.getContent(), response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getOutputStream().flush();
				response.getOutputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	// @RequiresPermissions("calendar:update")
	@RequestMapping(value = "update", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String update(@Valid @ModelAttribute("calendar") Calendar calendar, RedirectAttributes redirectAttributes, HttpSession session) {
		try {
			if (calendar.getCalendarType() != null && StringUtils.isNotBlank(calendar.getCalendarType().getId())) {
				CalendarType calendarType = calendarTypeService.getCalendarType(calendar.getCalendarType().getId());
				calendar.setBackgroundColor(calendarType.getBackgroundColor());
			} else {
				return ajaxMsg("编辑失败,日程类型未选择", false, null);
			}
			if (calendar.getUser() == null || StringUtils.isBlank(calendar.getUser().getId())) {
				calendar.setUser(new User(BasicController.getCurrentUserId()));
			}
			calendarService.saveCalendar(calendar);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("编辑失败[" + e.getMessage() + "]", false, null);
		}
		return ajaxMsg("编辑成功", true, null);
	}

	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(@ModelAttribute("calendar") Calendar calendar, Model model) {
		if (calendar.getAllDay() == null || calendar.getAllDay() != BasicConstants.NO_INT) {
			calendar.setAllDay(BasicConstants.YES_INT);
		}
		List<CalendarType> typeList = calendarTypeService.getCalendarTypes(BasicController.getCurrentUserId());
		model.addAttribute("calendar", calendar);
		model.addAttribute("typeList", typeList);
		return "basic/calendar-input";
	}

	@RequestMapping(value = "newCalendar", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String newCalendar(@ModelAttribute("calendar") Calendar calendar, Model model, RedirectAttributes redirectAttributes,
			HttpSession session) {
		try {
			if (calendar.getAllDay() == null || calendar.getAllDay() != BasicConstants.NO_INT) {
				calendar.setAllDay(BasicConstants.YES_INT);
			}
			calendar.setUser(new User(BasicController.getCurrentUserId()));
			calendarService.saveCalendar(calendar);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("新建失败[" + e.getMessage() + "]", false, null);
		}
		return ajaxMsg("新建成功", true, null);
	}

	/**
	 * 日程拖动，开始时间和结束时间都改变
	 * 
	 * @param calendar
	 * @param daydiff
	 * @param minudiff
	 * @param redirectAttributes
	 * @param session
	 * @return
	 * @throws ParseException
	 */
	@SuppressWarnings("static-access")
	@RequestMapping(value = "dragDrop", method = RequestMethod.POST)
	@ResponseBody
	public String dragDrop(@Valid @ModelAttribute("calendar") Calendar calendar,
			@RequestParam(value = "daydiff", defaultValue = "0") int daydiff,
			@RequestParam(value = "minudiff", defaultValue = "0") int minudiff,
			@RequestParam(value = "allday", defaultValue = "false") boolean allday, RedirectAttributes redirectAttributes,
			HttpSession session) throws ParseException {
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
		if (calendar.getAllDay() == (allday ? BasicConstants.YES_INT : BasicConstants.NO_INT)) {
			calendar.setStart(new Timestamp(new DateTime(calendar.getStart()).plusDays(daydiff).plusMinutes(minudiff).getMillis()));
			if (calendar.getEnd() != null) {
				calendar.setEnd(new Timestamp(new DateTime(calendar.getEnd()).plusDays(daydiff).plusMinutes(minudiff).getMillis()));
			}
		} else {
			calendar.setAllDay(allday ? BasicConstants.YES_INT : BasicConstants.NO_INT);
			if (allday) {
				calendar.setStart(new Timestamp(System.currentTimeMillis()).valueOf(new DateTime(calendar.getStart())
						.toString("yyyy-MM-dd 00:00:00")));
				if (calendar.getEnd() != null) {
					calendar.setEnd(new Timestamp(System.currentTimeMillis()).valueOf(new DateTime(calendar.getEnd())
							.toString("yyyy-MM-dd 23:59:00")));
				} else {
					calendar.setEnd(new Timestamp(System.currentTimeMillis()).valueOf(new DateTime(calendar.getStart())
							.toString("yyyy-MM-dd 23:59:00")));
				}
			} else {
				calendar.setStart(new Timestamp(new DateTime(sf.parse(new DateTime(calendar.getStart()).toString("yyyy-MM-dd 00:00:00")))
						.plusDays(daydiff).plusMinutes(minudiff).getMillis()));
				calendar.setEnd(new Timestamp(new DateTime(calendar.getStart()).plusDays(0).plusMinutes(2*60).getMillis()));
			}
		}
		try {
			calendarService.saveCalendar(calendar);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("编辑失败[" + e.getMessage() + "]", false, null);
		}
		return ajaxMsg("编辑成功", true, null);
	}

	/**
	 * 日程的缩放，只改变“结束时间”
	 * 
	 * @param calendar
	 * @param daydiff
	 * @param minudiff
	 * @param redirectAttributes
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "resize", method = RequestMethod.POST)
	@ResponseBody
	public String resize(@Valid @ModelAttribute("calendar") Calendar calendar,
			@RequestParam(value = "daydiff", defaultValue = "0") int daydiff,
			@RequestParam(value = "minudiff", defaultValue = "0") int minudiff, RedirectAttributes redirectAttributes, HttpSession session) {
		try {
			if (calendar.getEnd() != null) {
				calendar.setEnd(new Timestamp(new DateTime(calendar.getEnd()).plusDays(daydiff).plusMinutes(minudiff).getMillis()));
			} else {
				calendar.setEnd(new Timestamp(new DateTime(calendar.getStart()).plusDays(daydiff).plusMinutes(minudiff).getMillis()));
			}
			calendarService.saveCalendar(calendar);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("编辑失败[" + e.getMessage() + "]", false, null);
		}
		return ajaxMsg("编辑成功", true, null);
	}

	// @RequiresPermissions({ "calendar:delete", "calendar:update" })
	@RequestMapping(value = "delete/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes, HttpSession session) {
		calendarService.deleteCalendar(id);
		return ajaxMsg("删除成功", true, null);
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void getCalendar(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("calendar", calendarService.getCalendar(id));
		}
	}

	@InitBinder
	public void InitBinder(WebDataBinder dataBinder) {
		dataBinder.registerCustomEditor(Timestamp.class, new PropertyEditorSupport() {
			public void setAsText(String value) {
				try {
					if (value.length() == 19)
						setValue(new Timestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value).getTime()));
					else if (value.length() == 16)
						setValue(new Timestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(value).getTime()));
					else if (value.length() == 13)
						setValue(new Timestamp(new SimpleDateFormat("yyyy-MM-dd HH").parse(value).getTime()));
					else if (value.length() == 10)
						setValue(new Timestamp(new SimpleDateFormat("yyyy-MM-dd").parse(value).getTime()));
					else if (value.length() == 7)
						setValue(new Timestamp(new SimpleDateFormat("yyyy-MM").parse(value).getTime()));
				} catch (ParseException e) {
					setValue(null);
				}
			}

			public String getAsText() {
				return new SimpleDateFormat("yyyy-MM-dd HH:mm").format((Timestamp) getValue());
			}

		});
	}
}
